import Axios from 'axios'
import { baseURL } from '@/config/index'
import { Message } from 'element-ui'

const http = Axios.create({
  baseURL,
  timeout: 30 * 1000
  // headers: {
  //   post: {
  //     'Content-Type': 'multipart/form-data'
  //   }
  // }
})

http.interceptors.request.use(
  cfg => {
    console.log('axios request:')
    console.dir(cfg)
    return cfg
  },
  err => {
    console.log('axios err request:')
    console.dir(err)
    return Promise.reject(err)
  }
)
const delayMessage = msg => {
  let isShow = true
  setTimeout(() => {
    isShow && Message.error(msg)
  })
  return () => {
    isShow = false
  }
}
http.interceptors.response.use(
  res => {
    console.log('axios response:')
    console.dir(res)
    const { code, content, msg } = res.data
    if (code === 200 && content) return { data: content }
    if (msg) return { stopMessage: delayMessage(msg) }
    return {}
  },
  err => {
    console.log('axios err response:')
    console.dir(err)
    return Promise.reject({ err, stopMessage: delayMessage('网络异常！') })
  }
)

const jsonToFormData = json => {
  const fd = new FormData()
  for (const key in json) {
    fd.append(key, json[key])
  }
  return fd
}
const post = (url, data, isFormData) => {
  if (isFormData) {
    return http.post(url, data)
  } else {
    return http.post(url, jsonToFormData(data))
  }
}

export { http, post }
